package javango.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.Inject;
import com.google.inject.Injector;
import javango.api.MethodObjectParams;
import javango.api.Url;
import javango.api.Urls;
import javango.http.HttpException;
import javango.http.HttpRequest;

public class SubappUrl implements Url {
	private final static Log log = LogFactory.getLog(SubappUrl.class);

	@Inject
	Injector injector;
	
	public String pattern;
	protected Urls subUrl;
	protected Class<? extends Urls> subUrlsClass;

	// cached copies of the pattern
	protected Pattern p;

	
	public SubappUrl(Injector injector, String pattern, Class<? extends Urls> urlsClass) {
		super();
		this.injector = injector;
		this.subUrlsClass = urlsClass;
		this.setPattern(pattern);
		
	}
		
	@Override
	public String toString() {
		return "SubUrl: '" + this.pattern + "'";
	}
	
	public boolean matches(String url) {
		Matcher m = p.matcher(url);
		if (!m.lookingAt()) return false;
		String suburl = m.replaceFirst("");
		for (Url u : getSubUrl().getUrlPatterns()) {
			if( u.matches(suburl)) return true;
		}
		return false;
	}
	
	public MethodObjectParams getMethodObjectParams(String url, HttpRequest req) throws HttpException {
		Matcher m = p.matcher(url);
		if (m.lookingAt()) {
			String suburl = m.replaceFirst("");
			for (Url u : getSubUrl().getUrlPatterns()) {
				if( u.matches(suburl)) {
					return u.getMethodObjectParams(suburl, req);
				}
			}
		}
		
		log.warn("Called execute on url,  but pattern did not match: " + url);
		return null;
	}

	protected String getPattern() {
		return pattern;
	}

	protected void setPattern(String pattern) {
		p = Pattern.compile(pattern);
		this.pattern = pattern;
	}
	
	protected Urls getSubUrl() {
		if (subUrl == null) {
			subUrl = injector.getInstance(subUrlsClass);
		}
		return subUrl;
	}
}
